<template>
  <div :id="id" class="vditor-preview"></div>
</template>

<script setup>
import Vditor from 'vditor'
import 'vditor/dist/index.css'

const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  id: {
    type: String,
    default: 'vditor-container'
  },
  mode: {
    type: String,
    default: 'preview', // 'edit' 或 'preview'
    validator: (val) => ['edit', 'preview'].includes(val)
  }
})

const emit = defineEmits(['update:outline'])

const contentEditor = ref(null)

// 初始化预览模式
const initPreview = () => {
  nextTick(() => {
    const element = document.getElementById(props.id)
    if (!element) return

    Vditor.preview(
        element,
        props.content,
        {
          speech: { enable: false },
          cache: { enable: false },
          width: '100%',
          hljs: {
            style: 'atom-one-dark',
            lineNumber: true,
            enable: true
          },
          anchor: 1,
          after: () => {
            const tocTags = ['H1', 'H2', 'H3', 'H4']
            const childNodes = element.children
            const tocArray = []

            for (let i = 0; i < childNodes.length; i++) {
              const node = childNodes[i]
              if (tocTags.includes(node.tagName)) {
                const id = node.getAttribute('id')
                tocArray.push({
                  id: id,
                  text: node.textContent.trim(),
                  level: Number(node.tagName.substring(1)),
                  pos: node.offsetTop
                })
              }
            }
            emit('update:outline', tocArray)
          }
        }
    )
  })
}

// 初始化编辑模式
const initEditor = () => {
  contentEditor.value = new Vditor(
      props.id,
      {
        height: 360,
        value: props.content,
        mode: 'sv',
        toolbarConfig: { pin: false },
        cache: { enable: false },
        preview: {
          hljs: {
            style: 'atom-one-dark',
            lineNumber: true
          }
        },
        input: (value) => {
          emit('update:content', value)
        }
      }
  )
}

// 监听模式变化
watch(() => props.mode, (newVal) => {
  const element = document.getElementById(props.id)
  if (!element) return

  // 清除原有内容
  element.innerHTML = ''

  if (newVal === 'edit') {
    initEditor()
  } else {
    initPreview()
  }
})

onMounted(() => {
  if (props.mode === 'edit') {
    initEditor()
  } else {
    initPreview()
  }
})
</script>

<style scoped>
.vditor-preview {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 优化移动端显示 */
@media (max-width: 768px) {
  .vditor-preview {
    padding: 12px;
  }
}
</style>
